import axios from 'axios'
import router from "@/router";
import { ElMessage } from 'element-plus';

var instance = axios.create({
  baseURL: 'https://tianji.unspace.cn/cgi/api',
  timeout: 80000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;',
  }
})

//请求拦截器 
instance.interceptors.request.use((config: any) => {
  // const token = window.localStorage.getItem('token');
  // token && (config.headers.Authorization = token)
  // if (config.method === 'POST') {
  //     config.data = JSON.stringify(config.data);
  // }

  const token = sessionStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  return config;
}, (error) =>
  Promise.reject(error));

//响应拦截器
instance.interceptors.response.use((response) => {
  if ([-201, -205, -206, -207, -208, -209].includes(response.data.code)) {
    ElMessage({
      message: `${response.data.msg}`,
      type: 'warning'
    })
  } else if ([-202].includes(response.data.code)) {
    ElMessage({
      message: `${response.data.msg}`,
      type: 'warning'
    })
    router.push({
      path: '/Sign'
    })
  }
  return response.data;
}, (error) => {
  if (error.response && error.response.status) {
    return Promise.reject(error);
  }
  return Promise.reject(error);
});

export default instance;